package com.example.demo.aop;

import com.alibaba.fastjson.JSONObject;

import com.example.demo.mapper.OperateLogMapper;
import com.example.demo.pojo.OperateLog;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect//切面类
//aop基于代理
public class LogAspect {

    @Autowired
    private HttpServletRequest request;


    @Autowired
    private OperateLogMapper operateLogMapper;

    //环绕通知
    @Around("@annotation(com.example.demo.anno.Log)")//表示环绕带有 Log注解的方法
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //操作人Id(账号) - 登录人
        String  account = (String) request.getSession().getAttribute("user");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //操作类名
        String className = joinPoint.getTarget().getClass().getName();//拿到目标对象.拿到类对象.拿到类名(反射)

        //操作方法名
        String methodName = joinPoint.getSignature().getName();//获取方法签名.获取方法名(反射)

        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long begin = System.currentTimeMillis();
        //调用原始目标方法运行
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();


        //方法返回值
        String returnValue = JSONObject.toJSONString(result);

        //操作耗时
        Long costTime = end - begin;


        //记录操作日志
        OperateLog operateLog = new OperateLog(null,account,operateTime,className,methodName,methodParams,returnValue,costTime);
        operateLogMapper.insert(operateLog);

        log.info("AOP记录操作日志:{}",operateLog);

        return result;
    }
}
